package com.showcai.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.showcai.dao.CertificateMapper;
import com.showcai.module.*;
import com.showcai.myRunTime.MyRunTimeExcption;
import com.showcai.result.ReturnCode;
import com.showcai.service.*;
import com.showcai.util.DateUtil;
import com.showcai.util.GenerateID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Baggio on 2018-9-14.
 */
@Service
public class CertificateServiceImpl extends ServiceBase implements CertificateService {

    @Autowired
    CertificateClassifyService certificateClassifyService;
    @Autowired
    CertificateBatchService certificateBatchService;
    @Autowired
    CertificatePackService certificatePackService;
    @Autowired
    CertificateMapper certificateMapper;
    @Autowired
    UserService userService;
    @Autowired
    ProductEntityService productEntityService;

    @Override
    public List<Certificate> getCertificateList(Map<String, String> map) throws MyRunTimeExcption {
        return null;
    }

    @Override
    public List<Certificate> getCertificateListFromPackByUserId(Long userId) throws MyRunTimeExcption {
        return certificateMapper.getCertificateListFromPackByUserId(userId);
    }

    @Override
    public void createCertificate(CertificateBatch certificateBatch) {
        CertificateClassify certificateClassify = certificateClassifyService.selectCertificateClassifyById(certificateBatch.getCertificateClassifyId());
        Certificate certificate = new Certificate();
        certificate.setBalance(certificateClassify.getPrice());
        certificate.setCreateTime(new Date());
        certificate.setStatus(Certificate.CERTIFICATE_STATUS_NOT_ACTIVATION);
        certificate.setBatchId(certificateBatch.getBatchId());
        if (certificateClassify.getCertificateIdInterval() == 0) {
            certificate.setCertificateStartDate(certificateBatch.getStartDate());
            certificate.setCertificateEndDate(certificateBatch.getEndDate());
        }
        if (certificateClassify.getCertificateIdInterval() > 0) {
            certificate.setCertificateStartDate(new Date());
            certificate.setCertificateEndDate(DateUtil.addDay(new Date(), certificateClassify.getCertificateIdInterval()));
        }
        for (int i = 0; i < certificateBatch.getAmount(); i++) {
            certificate.setCertificateId(GenerateID.getRandomNum(8,false));
            certificateMapper.insertCertificate(certificate);
        }

    }

    @Override
    public Certificate modifyCertificate(Certificate certificate) throws MyRunTimeExcption {
        if (certificate.getTid() == null) {
            CertificateBatch certificateBatch = certificateBatchService.getCertificateBathByBatchId(certificate.getBatchId());
            createCertificate(certificateBatch);
            return null;
        }
        certificateMapper.updateByPrimaryKeySelective(certificate);
        return null;
    }


    @Override
    public Certificate getCertificateInfo(String certificateId) throws MyRunTimeExcption {
        return null;
    }

    @Override
    public List<Certificate> getUsedableCertificate(Long userId, List<Long> productEntityIdList) throws MyRunTimeExcption {
        return null;
    }

    @Override
    public Certificate userGainCertificate(Long userId, Long productEntityId) throws MyRunTimeExcption {
        Certificate certificate=null;
        User user = userService.getUserById(userId);
        if (user == null) {
            throw new MyRunTimeExcption(ReturnCode.USER_IS_INEXISTENCE);
        }

        ProductEntity productEntity=productEntityService.getProductEntityById(productEntityId);
        if(productEntity==null){
            throw new MyRunTimeExcption(ReturnCode.PRODUCT_ENTITY_IS_INEXISTENCE);
        }

        CertificateClassify certificateClassify = certificateClassifyService.selectCertificateClassifyByProductEntityId(productEntityId);
if(certificateClassify==null){
    throw new MyRunTimeExcption(ReturnCode.CERTIFICATECLASSIFY_IS_INEXISTENCE);
}
        Map<String,String> map=new HashMap<>();
        map.put("certificateClassifyId",String.valueOf(certificateClassify.getTid()));
        List<CertificateBatch> certificateBatchList=certificateBatchService.getCertificateBatchList(map);
if(certificateBatchList==null ||certificateBatchList.size()==0){
    throw new MyRunTimeExcption(ReturnCode.CERTIFICATE_BATCH_IS_INEXISTENCE);
}
        //立即生成的
        if(certificateClassify.getCertificateCreateType()==CertificateClassify.CREATE_TYPE_NOW){
            for (CertificateBatch certificateBatch:certificateBatchList
                 ) {
                certificate= certificateMapper.getCertificateByCertificateBatchId(certificateBatch.getBatchId());
                if(certificate!=null){
                    break;
                }
            }

        }
        //销售时生成的
        if(certificateClassify.getCertificateCreateType()==CertificateClassify.CREATE_TYPE_SELE){
            certificate=new Certificate();
            certificate.setBatchId(certificateBatchList.get(0).getBatchId());
            certificate.setCreateTime(new Date());
            certificate.setBalance(certificateClassify.getPrice());
            certificate.setStatus(Certificate.CERTIFICATE_STATUS_NOT_ACTIVATION);
            certificate.setCertificateId(GenerateID.getRandomNum(8,false));
            if (certificateClassify.getCertificateIdInterval() == 0) {
                certificate.setCertificateStartDate(certificateBatchList.get(0).getStartDate());
                certificate.setCertificateEndDate(certificateBatchList.get(0).getEndDate());
            }
            if (certificateClassify.getCertificateIdInterval() > 0) {
                certificate.setCertificateStartDate(new Date());
                certificate.setCertificateEndDate(DateUtil.addDay(new Date(), certificateClassify.getCertificateIdInterval()));
            }
            certificateMapper.insertCertificate(certificate);
        }
        activationCertificate(certificate.getCertificateId(),userId);
        return certificate;
    }

    @Override
    public List<Certificate> getGetableCertificate() throws MyRunTimeExcption {
        return null;
    }

    @Override
    public List<CertificateUserdLog> getCertificateUserdLogList(Map<String, String> map) throws MyRunTimeExcption {
        return null;
    }

    @Override
    public Certificate getCertificateByCertificateId(String certificateId) {
        return certificateMapper.getCertificateByCertificateId(certificateId);
    }

    @Override
    public PageInfo getPageInfoCertificateList(Map<String, String> map) {
        Integer page = Integer.parseInt(map.get("page"));
        Integer pageSize = Integer.parseInt(map.get("pageSize"));
        PageHelper.startPage(page, pageSize);
        List<Certificate> certificateList = certificateMapper.getPageInfoCertificateList(map);
        PageInfo<Certificate> pageinfo = new PageInfo<>(certificateList);
        return pageinfo;
    }

    @Override
    public void activationCertificate(String certificateId, Long userId) throws MyRunTimeExcption {
        User user = userService.getUserById(userId);
        if (null == user) {
            throw new MyRunTimeExcption("请先登录");
        }

        Certificate certificate = getCertificateByCertificateId(certificateId);
        if (null == certificate) {
            throw new MyRunTimeExcption("没有发现此卡券");
        }
        if(certificate.getStatus()!=Certificate.CERTIFICATE_STATUS_NOT_ACTIVATION){
            throw new MyRunTimeExcption("此卡券异常不能激活");
        }

        CertificateBatch certificateBatch = certificateBatchService.getCertificateBathByBatchId(certificate.getBatchId());
        if (null == certificateBatch) {
            throw new MyRunTimeExcption("您的卡券没有对应的批次");
        }
        if(certificateBatch.getStatus()!=Certificate.STATUS_VALID){
            throw new MyRunTimeExcption("此卡券批次异常不能激活");
        }


        CertificateClassify certificateClassify = certificateClassifyService.selectCertificateClassifyById(certificateBatch.getCertificateClassifyId());
        // 更新卡券时间和状态
        if (certificateClassify.getCertificateIdInterval() > 0) {
            certificate.setCertificateStartDate(new Date());
            certificate.setCertificateEndDate(DateUtil.addDay(new Date(), certificateClassify.getCertificateIdInterval()));
        }

        if (DateUtil.compareDate(certificate.getCertificateEndDate(), new Date()) < 1) {
            throw new MyRunTimeExcption("卡券已经过期！");
        }
        certificate.setStatus(Certificate.STATUS_VALID);
        modifyCertificate(certificate);


        // 加入用户卡包
        CertificatePack certificatePack = new CertificatePack();
        certificatePack.setStatus(CertificatePack.STATUS_VALID);
        certificatePack.setCreateTime(new Date());
        certificatePack.setUserId(userId);
        certificatePack.setCertificateId(String.valueOf(certificateId));
        certificatePackService.modifyCertificatePack(certificatePack);

    }

    @Override
    public void usedCertificate(String certificateId) throws MyRunTimeExcption {

        Certificate certificate=getCertificateByCertificateId(certificateId);
        if(certificate==null){
            throw new MyRunTimeExcption("卡券不存在！");
        }
        certificate.setStatus(Certificate.STATUS_USERD);
        certificateMapper.updateByPrimaryKeySelective(certificate);
        // 加入用户卡包
        CertificatePack certificatePack = certificatePackService.getCertificateListFromPackByCertificateId(certificateId);
        certificatePack.setStatus(CertificatePack.STATUS_USERD);
        certificatePackService.modifyCertificatePack(certificatePack);
    }

    @Override
    public void verifyExperience(String certificateId,Long organizationId) throws MyRunTimeExcption {
        Certificate certificate=getCertificateByCertificateId(certificateId);
        if(certificate==null){
            throw new MyRunTimeExcption("卡券不存在！");
        }
        CertificateBatch certificateBatch = certificateBatchService.getCertificateBathByBatchId(certificate.getBatchId());
        if (null == certificateBatch) {
            throw new MyRunTimeExcption("您的卡券没有对应的批次");
        }
        if(certificateBatch.getStatus()!=Certificate.STATUS_VALID){
            throw new MyRunTimeExcption("此卡券批次异常不能激活");
        }


        CertificateClassify certificateClassify = certificateClassifyService.selectCertificateClassifyById(certificateBatch.getCertificateClassifyId());
        ;
        WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
        CertificateVerifyService certificateVerifyService = (CertificateVerifyService) wac.getBean(certificateClassify.getExecClass());
        Map<String,String> map=new HashMap<>();
       map.put("organizationId",String.valueOf(organizationId));
       map.put("certificateId",certificateId);
        certificateVerifyService.verifyCertificate(map);

    }
}
